package topcoder;

import java.util.*;

public class NextOrPrev {
	
	class Point implements Comparable<Point>{
		int x, y;
		
		public Point(int x, int y) {
			this.x = x;
			this.y = y;
		}
		
		@Override
		public int compareTo(Point o) {
			if (x < o.x)
				return -1;
			if (x > o.x)
				return 1;
			if (y < o.y)
				return -1;
			if (y > o.y)
				return 1;
			return 0;
		}
	}
	
	public int getMinimum(int nextCost, int prevCost, String start, String goal) {
		int n = start.length();
		List<Point> points = new ArrayList<Point>();
		
		for (int i = 0; i < n; i++)
			points.add(new Point( (int)start.charAt(i), (int)goal.charAt(i) ));
		
		Collections.sort(points);
		
		
		int cost = 0;
		int y = -1;
		for (Point p : points) {
			if (p.y < y)
				return -1;
			y = p.y;
			
			int d = p.y - p.x;
			if (d > 0)
				cost += d * nextCost;
			if (d < 0)
				cost += (-d) * prevCost;
		}
		
		return cost;
	}

	public int getMinimum2(int nextCost, int prevCost, String start, String goal) {
		int n = start.length();
		int[] A = new int[n];
		int[] B = new int[n];
		
		for (int i = 0; i < n; i++) {
			A[i] = (int) start.charAt(i);
			B[i] = (int) goal.charAt(i);
		}
		int c = 0;
		
		HashSet<Integer> Dnext = new HashSet<Integer>();
		HashSet<Integer> Dprev = new HashSet<Integer>();
		
		for (int i = 0; i < n; i++) {
			int d = B[i] - A[i];
			
			if (d > 0) {
				for (int j = 0; j < i; j++) {
					if ( (B[j] - A[j] > 0) ){
						if ( A[j] > A[i] && B[j] < B[i] )
							return -1;
					}
				}
				
				if ( Dnext.contains(A[i]) && Dnext.contains(B[i]) )
					return -1;
				
				if ( Dprev.contains(A[i]) || Dprev.contains(B[i]) )
					return -1;
				
				for (int j = A[i] + 1; j < B[i]; j++){
					if (Dprev.contains(j))
						return -1;
					Dnext.add(j);
				}
				
				c += d * nextCost;
			}
			else if (d < 0) {
				for (int j = 0; j < i; j++) {
					if ( (B[j] - A[j] < 0) ){
						if ( A[j] > A[i] && B[j] < B[i] )
							return -1;
					}
				}
				
				if ( Dprev.contains(A[i]) && Dprev.contains(B[i]) )
					return -1;
				
				if ( Dnext.contains(A[i]) || Dnext.contains(B[i]) )
					return -1;
				
				for (int j = A[i] + 1; j < B[i]; j++){
					if (Dnext.contains(j))
						return -1;
					Dprev.add(j);
				}
			
				c += (-d) * prevCost;
			}
		}
		
		
		return c;
	}
	
	public static void main(String[] args) {
		NextOrPrev r = new NextOrPrev();
		System.out.println(r.getMinimum(126, 311, "yovlkwpjgsna", "zpwnkytjisob"));
	}
}
